package com.tfb.service.utility;

import java.security.MessageDigest;
import java.util.regex.Pattern;

public class MD5Util {

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static String MD5(String s) {
        if (s == null)
            return null;
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();

            // convert the byte to hex format method 1
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < md.length; i++) {
                sb.append(Integer.toString((md[i] & 0xff) + 0x100, 16).substring(1));
            }
            // convert the byte to hex format method 2
            StringBuilder hexString = new StringBuilder();
            for (int i = 0; i < md.length; i++) {
                String hex = Integer.toHexString(0xff & md[i]);
                if (hex.length() == 1)
                    hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (Exception e) {
            return null;
        }
    }
}
